/*
	This file is part of the OdinMS Maple Story Server
    Copyright (C) 2008 Patrick Huy <patrick.huy@frz.cc>
		       Matthias Butz <matze@odinms.de>
		       Jan Christian Meyer <vimes@odinms.de>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as
    published by the Free Software Foundation version 3 as published by
    the Free Software Foundation. You may not use, modify or distribute
    this program under any other version of the GNU Affero General Public
    License.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
package client.command;

import java.rmi.RemoteException;
import client.MapleCharacter;
import client.MapleClient;
import client.MapleStat;
import java.sql.ResultSet;
import java.util.HashMap;
import net.channel.ChannelServer;
import scripting.npc.NPCScriptManager;
import server.MapleAchievements;
import tools.MaplePacketCreator;
import tools.StringUtil;

class PlayerCommands {
    static boolean execute(MapleClient c, String[] splitted, char heading) {
        splitted[0] = splitted[0].toLowerCase();
        MapleCharacter player = c.getPlayer();
        ChannelServer cserv = c.getChannelServer();
        if (splitted[0].equals("command") || splitted[0].equals("commands") || splitted[0].equals("help")) {
            player.message("================================================================");
            player.message(" HoldenMs Player Commands");
            player.message("================================================================");
            player.message("@checkstats - | - Displays your stats.");
            player.message("@save - | - Saves your progress.");
            player.message("@expfix - | - Fixes your negative experience.");
            player.message("@dispose - | - Unstucks you.");
            player.message("@emo - | - Sets your HP zero.");
            player.message("@rebirth - | - Resets your HP/MP and sets your level to 1 to be stronger.");
            player.message("@str/@dex/@int/@luk <number> - | - Automatically add AP to your stats.");
            player.message("@gm <message> - | - Sends a message to the GM's online.");
            player.message("@revive - | - Revives anyone on the channel besides yourself.");
            player.message("@cody - | - he is the Job Advancer Plus World Teleporter.");
            player.message("@gmlist - | - the official GM List for HoldenMS.");
            player.message("@achievements - | - Shows your finished Achievements.");
            player.message("@votepoints - | - Check to see how much vote points you have.");
            player.message("@world - | - Chat with the World");
        } else if (splitted[0].equals("checkstats")) {
            player.message("Your stats are:");
            player.message("Str: " + player.getStr());
            player.message("Dex: " + player.getDex());
            player.message("Int: " + player.getInt());
            player.message("Luk: " + player.getLuk());
            player.message("Available AP: " + player.getRemainingAp());
            player.message("Rebirths: " + player.getReborns());
        } else if (splitted[0].equals("save")) {
            player.saveToDB(true);
            player.message("Saved to the HoldenMs DB");
            player.message("this gets backed up every 6 hours!");
        } else if (splitted[0].equals("expfix")) {
            player.setExp(0);
            player.updateSingleStat(MapleStat.EXP, player.getExp());
        } else if (splitted[0].equals("dispose")) {
            NPCScriptManager.getInstance().dispose(c);
            player.message("You have been disposed.");
        } else if (splitted[0].equals("emo")) {
            player.setHp(0);
            player.updateSingleStat(MapleStat.HP, 0);
            cserv.broadcastPacket(MaplePacketCreator.serverNotice(6, player.getName()+ " is Emo!"));
        } else if (splitted[0].equals("rebirth") || splitted[0].equals("reborn")) {
            if (player.getLevel() >= 200) {
                player.doReborn();
            } else {
                player.message("You must be at least level 200.");
            }
        } else if (splitted[0].equals("str") || splitted[0].equals("dex") || splitted[0].equals("int") || splitted[0].equals("luk") || splitted[0].equals("hp") || splitted[0].equals("mp")) {
            if (splitted.length != 2) {
                player.message("Syntax: /<Stat> <amount>");
                player.message("Stat: <STR> <DEX> <INT> <LUK> <HP> <MP>");
                return true;
            }
            int x = Integer.parseInt(splitted[1]), max = 30000;
            if (x > 0 && x <= player.getRemainingAp() && x < Short.MAX_VALUE) {
                if (splitted[0].equals("str") && x + player.getStr() < max) {
                    player.addAP(c, 1, x);
                } else if (splitted[0].equals("dex") && x + player.getDex() < max) {
                    player.addAP(c, 2, x);
                } else if (splitted[0].equals("int") && x + player.getInt() < max) {
                    player.addAP(c, 3, x);
                } else if (splitted[0].equals("luk") && x + player.getLuk() < max) {
                    player.addAP(c, 4, x);
                } else if (splitted[0].equals("hp") && x + player.getMaxHp() < max) {
                    player.addAP(c, 5, x);
                } else if (splitted[0].equals("mp") && x + player.getMaxMp() < max) {
                    player.addAP(c, 6, x);
                } else {
                    player.message("Make sure the stat you are trying to raise will not be over " + Short.MAX_VALUE + ".");
                }
            } else {
                player.message("Please make sure your AP is valid.");
            }
        } else if (splitted[0].equals("gm")) {
            if (splitted.length < 2) {
                return true;
            }
            try {
                c.getChannelServer().getWorldInterface().broadcastGMMessage(null, MaplePacketCreator.serverNotice(6, "Channel: " + c.getChannel() + "  " + player.getName() + ": " + StringUtil.joinStringFrom(splitted, 1)).getBytes());
            } catch (RemoteException ex) {
                c.getChannelServer().reconnectWorld();
            }
            player.message("Message sent.");
        } else if (splitted[0].equals("revive")) {
            if (splitted.length == 2) {
                MapleCharacter victim = c.getChannelServer().getPlayerStorage().getCharacterByName(splitted[1]);
                if (player != victim) {
                    if (player.getMeso() >= 50000000) { // 50 mil
                        if (victim != null) {
                            if (!victim.isAlive()) {
                                victim.setHp((victim.getMaxHp() / 2));
                                player.gainMeso(-50000000, true);
                                victim.updateSingleStat(MapleStat.HP, (victim.getMaxHp() / 2));
                                player.message("You have revived " + victim.getName() + ".");
                            } else {
                                player.message(victim.getName() + " is not dead.");
                            }
                        } else {
                            player.message("The player is not online.");
                        }
                    } else {
                        player.message("You need 50 million mesos to do this.");
                    }
                } else {
                    player.message("You can't revive yourself.");
                }
            } else {
                player.message("Syntax: /revive <player name>");
            }
        } else if (splitted[0].equals("cody")) {
            NPCScriptManager.getInstance().start(c, 9200000, null, null);
        } else if (splitted[0].equals("gmlist")) {
            player.message("Owners");
            player.message("L337 - Server Founder/Owner/Host/Dev");
            player.message("ThiefofDoom - Co Founder/Co Owner");
            player.message("Head GM");
            player.message("Winterfresh - Co Founder/ Co Host (shes L337's Sister)");
            player.message("GMs");
            player.message("Skittlez - Regular GM");
            player.message("--SPACE OPEN--");
    } else if (splitted[0].equals("goto")) {
            HashMap<String, Integer> maps = new HashMap<String, Integer>();
            maps.put("southperry", 60000);
            maps.put("amherst", 1010000);
            maps.put("henesys", 100000000);
            maps.put("ellinia", 101000000);
            maps.put("perion", 102000000);
            maps.put("kerning", 103000000);
            maps.put("lith", 104000000);
            maps.put("sleepywood", 105040300);
            maps.put("florina", 110000000);
            maps.put("orbis", 200000000);
            maps.put("happy", 209000000);
            maps.put("elnath", 211000000);
            maps.put("ludi", 220000000);
            maps.put("omega", 221000000);
            maps.put("korean", 222000000);
            maps.put("aqua", 230000000);
            maps.put("leafre", 240000000);
            maps.put("mulung", 250000000);
            maps.put("herb", 251000000);
            maps.put("nlc", 600000000);
            maps.put("shrine", 800000000);
            maps.put("showa", 801000000);
            maps.put("fm", 910000000);
            if (maps.containsKey(splitted[1])) {
                player.changeMap(cserv.getMapFactory().getMap(maps.get(splitted[1])), cserv.getMapFactory().getMap(maps.get(splitted[1])).getPortal(0));
            }
            if (player.inJail()) {
                player.inJail();
                player.message("hahaha, cant get out now!");
            }
    }else if (splitted[0].equalsIgnoreCase("achievements")) {
            player.message("Your finished achievements:");
            for (Integer i : c.getPlayer().getFinishedAchievements()) {
                player.message(MapleAchievements.getInstance().getById(i).getName() + " - " + MapleAchievements.getInstance().getById(i).getReward() + " NX.");
            }
    } else if (splitted[0].equals("votepoints")) {
       player.message("You have "+player.getVotepoints()+" points");
    } else if (splitted[0].equals("world")) {
        if (player.WorldChat()) {
            try {
                cserv.getWorldInterface().broadcastMessage(player.getName(), MaplePacketCreator.serverNotice(6, "["+player.getName()+"]"+ joinStringFrom(splitted, 1)).getBytes());
            } catch (Exception e) {
                cserv.reconnectWorld();
            }
        } else {
            player.message("Sorry your not over Level 70.");
        }
    }  else if (splitted[0].equals("online")) {
            for (ChannelServer ch : ChannelServer.getAllInstances()) {
                String s = "Characters online (Channel " + ch.getChannel() + " Online: " + ch.getPlayerStorage().getAllCharacters().size() + ") : ";
                if (ch.getPlayerStorage().getAllCharacters().size() < 50) {
                    for (MapleCharacter chr : ch.getPlayerStorage().getAllCharacters()) {
                        s += MapleCharacter.makeMapleReadable(chr.getName()) + ", ";
                    }
                    player.message(s.substring(0, s.length() - 2));
                }
            }
    } else if (splitted[0].equals("fakerelog")) {
                    c.getSession().write(MaplePacketCreator.getCharInfo(player));
                    player.getMap().removePlayer(player);
                    player.getMap().addPlayer(player);

                }  else {
            if (player.gmLevel() == 0) {
                player.message("Player Command " + heading + splitted[0] + " does not exist.");
            }
            return false;
        }
        return true;
    }
       static String joinStringFrom(String arr[], int start) {
        StringBuilder builder = new StringBuilder();
        for (int i = start; i < arr.length; i++) {
            builder.append(arr[i]);
            if (i != arr.length - 1) {
                builder.append(" ");
            }
        }
        return builder.toString();
    }
}